import React, { Component } from 'react'
import '../../less/index.less'
import {TwsEditAssignmentStatus, TwsShowAssignmentStatus} from 'tws-antd'
import {message} from 'antd'

const GRADE_UNDEFINE = {
  text: '未打分',
  count: -1
}

class EditStatusBox extends Component {
  constructor (props) {
    super(props)
    this.state = {
      grade: 0,
      status: '',
      excellence: 0,
      disable: false
    }
  }

  buildReviewData () {
    const {quizId, assignmentId, review, studentId, taskId} = this.props
    const id = review.id
    const {grade, excellence} = this.state
    const excellenceGradle = 85
    const status = grade > excellenceGradle ? '优秀' : '已完成'
    return {grade, excellence, status, id, assignmentId, studentId, quizId, taskId}
  }

  disableEdit () {
    this.setState({disable: true})
  }

  enableEdit () {
    this.setState({disable: false})
  }

  updateGrade (e) {
    const grade = e.target.value
    const pattern = /^([0-9]{1,2}|100)$/
    if ((!isNaN(grade) && pattern.test(grade)) || grade === '') {
      this.setState({grade})
    } else {
      message.warning('分数范围是 1-100 哦')
    }
  }
  submitGrade () {
    const review = this.buildReviewData()
    this.disableEdit()
    this.props.updateReviewGrade(review, () => {
      this.enableEdit()
      message.success('成绩保存成功！')
    })
  }

  getStatus () {
    const reviewQuiz = this.props.review

    if (reviewQuiz.status) {
      return reviewQuiz.status
    } else {
      return '未完成'
    }
  }

  componentWillReceiveProps (nextProps) {
    const {review = {}} = nextProps
    const {grade} = review
    this.setState({
      grade: grade !== 0 && !grade ? GRADE_UNDEFINE.count : grade
    })
  }

  render () {
    const status = this.getStatus()
    const stateGrade = this.state.grade
    const grade = stateGrade === GRADE_UNDEFINE.count ? 0 : stateGrade
    const showGrade = stateGrade === GRADE_UNDEFINE.count ? GRADE_UNDEFINE.text : stateGrade

    return (<div>
      {this.props.isTutor
          ? <TwsEditAssignmentStatus grade={grade.toString()}
            disabled={this.props.disable ? this.props.disable : this.props.isSubmit ? this.state.disable : true}
            onBlur={this.submitGrade.bind(this)}
            onChangeGrade={this.updateGrade.bind(this)}
            status={status} />
          : <TwsShowAssignmentStatus grade={showGrade.toString()}
            status={status} />
            }
    </div>
    )
  }
}

export default EditStatusBox
